<?php
namespace app\seller\controller;
use think\Input;
class Settle extends Common{
    public function initialize(){
        parent::initialize();   
    }

    public function index(){
    	if(request()->isPost()){ 
            $map=''; 
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]);
                if($starttime >= $endtime){
                    return $result = ['code'=>-1,'msg'=>'开始日期晚于结束日期!','rel'=>1];
                }    
                $map= [$starttime,$endtime];  
            }
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');           
            $list=db('bill')
                    ->where(array('type'=>'shop','typeid'=>session('seller.id')))
                    ->whereTime('addtime',$map)
                    ->order('id desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();   
                foreach ($list['data'] as $k=>$v){
                    if($v['type']==='shop'){ 
                        $list['data'][$k]['type'] ='商户';
                    }else{
                        $list['data'][$k]['type'] ='未知类型';
                    }
                    if($v['paytype']==='bank'){
                        $list['data'][$k]['paytype']='银行卡'; 
                    }elseif ($v['paytype']==='wxpay') {
                        $list['data'][$k]['paytype']='微信'; 
                    }elseif ($v['paytype']==='alipay') {
                        $list['data'][$k]['paytype']='支付宝';   
                    }else{
                        $list['data'][$k]['type']=$v['paytype']; 
                    }
                    if($v['status']===0){ 
                        $list['data'][$k]['status'] ='<span class="red">代审核</span>';
                    }elseif($v['status']===1){
                        $list['data'][$k]['status'] ='<span class="gre">已成功</span>';
                    }else{
                        $list['data'][$k]['status'] ='<span class="red">未知类型</span>';
                    }
                    $list['data'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                    if($v['endtime']){
                        $list['data'][$k]['endtime'] = date('Y-m-d H:i:s',$v['endtime']);
                    }
                    
                }
                return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $this->assign('title','订单管理');
        return $this->fetch();
    }  
    public function ordermin(){   
        $this->assign('userid',input('userid')); 
        $this->assign('channelid',input('channelid')); 
        return $this->fetch();
    } 

    public function total(){
        if(request()->isPost()){ 
            $map='';
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1]);
                if($starttime >= $endtime){
                    return $result = ['code'=>-1,'msg'=>'开始日期晚于结束日期!','rel'=>1];
                }    
                $map= [$starttime,$endtime];  
            }             
            $shopid=session('seller.id');
            //当日条件
            $s_today = strtotime(date('Y-m-d',time()));
            $e_today = strtotime(date('Y-m-d',time()))+86399;
            $maps = [$s_today,$e_today]; 
            if($shopid){
                 if($this->seller['level'] == 2){
                    //商户订单总额
                    $payorder['order_total']=db('channel_order')->where('sagentid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('money');
                    //商户手续费
                    $payorder['income']=db('channel_order')->where('sagentid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('fei_sagent');
                    //提现申请 
                    $payorder['cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$map)->sum('cash');
                    //商户余额 
                    $payorder['shop_total']=number_format($payorder['income']-$payorder['cash'],2);
                    
                    //当日收入
                    //商户订单额
                    $payorder['today_order_total']=db('channel_order')->where('sagentid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('money');
                    //商户手续总费
                    $payorder['today_income']=db('channel_order')->where('sagentid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('fei_sagent');
                    //扣除手续费 商户余额
                    $today_cash=0;
                    $payorder['today_cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$maps)->sum('cash');
                    $payorder['today_shop_total']=$payorder['today_income']-$payorder['today_cash']; 
                }else{
                    //商户订单总额
                    $payorder['order_total']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('money');
                    //商户手续费
                    $payorder['income']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('fei_shop');
                    //提现申请 
                    $payorder['cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$map)->sum('cash');
                    //商户余额 
                    $payorder['shop_total']=number_format($payorder['order_total']-$payorder['income']-$payorder['cash'],2);
                    
                    //当日收入
                    //商户订单额
                    $payorder['today_order_total']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('money');
                    //商户手续总费
                    $payorder['today_income']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('fei_shop');
                    //扣除手续费 商户余额
                    $today_cash=0;
                    $payorder['today_cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$maps)->sum('cash');
                    $payorder['today_shop_total']=$payorder['today_order_total']-$payorder['today_income']-$payorder['today_cash']; 
                }
                // //商户订单总额
                // $payorder['order_total']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('money');
                // //商户手续费
                // $payorder['income']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$map)->sum('fei_shop');
                // //提现申请 
                // $payorder['cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$map)->sum('cash');
                // //商户余额 
                // $payorder['shop_total']=number_format($payorder['order_total']-$payorder['income']-$payorder['cash'],2);
                
                // //当日收入
                // //商户订单额
                // $payorder['today_order_total']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('money');
                // //商户手续总费
                // $payorder['today_income']=db('channel_order')->where('shopid',$shopid)->where('state',2)->where($where)->whereTime('addtime',$maps)->sum('fei_shop');
                // //扣除手续费 商户余额
                // $today_cash=0;
                // $payorder['today_cash']=db('bill')->where(array('type'=>'shop','typeid'=>$shopid))->whereTime('addtime',$maps)->sum('cash');
                // $payorder['today_shop_total']=$payorder['today_order_total']-$payorder['today_income']-$payorder['today_cash'];
                $payorders[0]=$payorder;
                return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$payorders,'rel'=>1];
            }else{
                return $result = ['code'=>1,'msg'=>'获取失败!','data'=>$payorders,'rel'=>1];
            }
       
        } 
    }

    

    public function add()
    {
        if(request()->isPost()) {
            $data = input('post.');
            //商户信息
            $shopinfo = db('shop')->where('id',session('seller.id'))->find();
            if($shopinfo['one_cash']){
                $area_money = explode('-', $shopinfo['one_cash']);
                $s_money = $area_money[0];
                $e_money = $area_money[1];
                if(!empty($s_money) && !empty($e_money)){
                    if($s_money <= $data['cash'] && $e_money >= $data['cash']){
                    }else{
                        $this->error('单笔提现额度：'.$s_money.'至'.$e_money.'元！','index');
                    }
                    if ($data['cash'] <= 0) {
                        $this->error('单笔提现至少为一分！','index');
                    }          

                }else{
                    $this->error('单笔提现额度设置错误！','index');
                }
                
            }else{
                $this->error('未设置单笔提现额度','index');
            }
            if($data['paypwd']){
                if(md5($data['paypwd']) !== $shopinfo['paypwd']){
                    $this->error('支付密码错误！','index');
                }
                unset($data['paypwd']);
            }else{
               $this->error('请输入支付密码！','index'); 
            }
            if($this->seller['level'] == 2){
                //商户代理手续费
                $income=db('channel_order')->where('sagentid',session('seller.id'))->where('state',2)->sum('fei_sagent');
                //扣除手续费 扣除提现申请 商户代理余额 
                $cash=db('bill')->where(array('type'=>'shop','typeid'=>session('seller.id')))->sum('cash');
                $shop_total=(float)$income-(float)$cash;
            }else{
                //商户余额 
                $order_total=db('channel_order')->where('shopid',session('seller.id'))->where('state',2)->sum('money');
                //商户手续费
                $income=db('channel_order')->where('shopid',session('seller.id'))->where('state',2)->sum('fei_shop');
                //扣除手续费 扣除提现申请 商户余额 187030.11
                $cash=db('bill')->where(array('type'=>'shop','typeid'=>session('seller.id')))->sum('cash');
                // var_dump($order_total);die;
                $shop_total=(float)$order_total-(float)$income-(float)$cash;
            }
            if($shopinfo['deposit']){
                if($shop_total-$data['cash'] < $shopinfo['deposit']){
                    $this->error('商户余额不足！','index');
                }
            }else{
               $this->error('保证金未设置！','index');  
            }
            $bankinfo = explode('|', $data['bankid']); 
            $data['bankid'] = $bankinfo[0];
            $data['payno'] = $bankinfo[1];
            $data['user'] = $bankinfo[2];
            $data['mobile'] = $bankinfo[3];
            $data['payname'] = $bankinfo[5].$bankinfo[4].$bankinfo[6];
            $data['paytype'] = $bankinfo[7];
            if($data['paytype'] == 'alipay'){
                $data['payment_img'] = $bankinfo[8];
            }elseif($data['paytype'] == 'wxpay'){
                $data['payment_img'] = $bankinfo[9];
            }
            if(!empty($bankinfo[10])){
                $data['idcard'] = $bankinfo[10];
            }
            $data['addtime'] = time();
            $data['type'] = 'shop';
            $data['typeid'] = session('seller.id');            
            $data['typename'] = $shopinfo['name'];                         
            // $data['paytype'] = '银行卡';
            $id = db('bill')->insertGetId($data);
            if($id){ 
                $this->success('申请成功！','index');
            }else{
                $this->error('申请失败！','index');
            }
        }else{
            $bankinfo = db('bill_bank')->where(array('typename'=>'shop','typeid'=>session('seller.id')))->select();
            $this->assign('bankinfo',$bankinfo);
            $this->assign('title','提现申请');
            return $this->fetch();
        }
    }

    public function addbank()
    {
        if(request()->isPost()) {
            $data = input('post.'); 
            $data['typename'] = 'shop'; 
            $data['typeid'] = session('seller.id');  
            $data['addtime'] = time(); 
            if($data['idcard']){
                if(!$this->is_idcard($data['idcard'])){
                    $this->error('请核对身份证号码！','addbank');
                } 
            }
            if(!$this->is_mobile($data['mobile'])){
                $this->error('请核对手机号码！','addbank');
            }
            if(empty($data['file'])){
                unset($data['file']);
            }
            // if($data['bankno']){
            //     if(!$this->is_bankno($data['bankno'])){
            //         $this->error('请核对银行卡账号！','addbank');
            //     }
            // }         
            $id = db('bill_bank')->insertGetId($data);
            if ($id) {
                $this->success('新增成功','index');
                // $result['msg'] = '新增成功!'; 
                // $result['url'] = url('banklist'); 
                // $result['code'] = 1;
            } else {
                $this->error('新增失败','index');
                // $result['msg'] = '新增失败!';
                // $result['url'] = url('banklist'); 
                // $result['code'] = 0;
            }
            // return json($result);
            // if($id){ 
            //     $this->success('添加成功！','index');
            // }else{
            //     $this->error('添加失败！','index');
            // }
        }else{
            $this->assign('title','添加收款账号');
            return $this->fetch();
        }
    }

    public function banklist()
    {
        if(request()->isPost()){ 
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');           
            $list=db('bill_bank')
                    ->where(array('typename'=>'shop','typeid'=>session('seller.id')))
                    ->order('id desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();  
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $list['data'][$k]['bankname'] = $v['address'].$v['bankname'].$v['branchname'];
                if($v['paytype']==='bank'){
                    $list['data'][$k]['paytype']='银行卡'; 
                }elseif ($v['paytype']==='wxpay') {
                    $list['data'][$k]['paytype']='微信'; 
                    $list['data'][$k]['payment_img']=$v['w_file']; 
                }elseif ($v['paytype']==='alipay') {
                    $list['data'][$k]['paytype']='支付宝';  
                    $list['data'][$k]['payment_img']=$v['a_file'];  
                }else{
                    $list['data'][$k]['type']=$v['paytype']; 
                }
            }  
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $this->assign('title','结算卡列表');
        return $this->fetch();
    }

    public function editbank($id='')
    {
        $bank = db('bill_bank');
        if(request()->isPost()){
            $data = input('post.');
            if(empty($data['file'])){
                unset($data['file']);
            }
            if(empty($data['w_file'])) {
                unset($data['w_file']);
            }
            if(empty($data['a_file'])) {
                unset($data['a_file']);
            }
            if ($bank->update($data)!==false) { 
                $this->success('修改成功!','banklist');
                // $result['msg'] = '修改成功!'; 
                // $result['url'] = url('banklist'); 
                // $result['code'] = 1;
            } else {
                $this->error('修改失败!','banklist');
                // $result['msg'] = '修改失败!';
                // $result['url'] = url('banklist'); 
                // $result['code'] = 0;
            }
            // return json($result);
            // if ($bank->update($data)!==false) { 
            //     $this->success('修改成功！','banklist');
            // } else {
            //     $this->error('修改失败！','banklist');
            // }
        }else{ 
            // var_dump($id);die;
            $bankinfo=$bank->where(array('id'=>$id))->find();
            $this->assign('bankinfo',$bankinfo); 
            return $this->fetch();
        }
    }

    public function delbank($id='')
    {
        $del=db('bill_bank')->delete($id);
        if($del){
            $this->success('删除成功！','banklist');
        }else{
            $this->error('删除失败！','banklist');
        }
        
    }


    public function is_idcard($id) 
    { 
      $id = strtoupper($id); 
      $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/"; 
      $arr_split = array(); 
      if(!preg_match($regx, $id)){ 
        return FALSE; 
      } 
       //检查15位
        if(15==strlen($id)){ 
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/"; 
            @preg_match($regx, $id, $arr_split); 
            //检查生日日期是否正确 
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4]; 
            if(!strtotime($dtm_birth)){ 
              return FALSE; 
            }else{ 
              return TRUE; 
            } 
            }else{ 
            //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/"; 
            @preg_match($regx, $id, $arr_split); 
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4]; 
            //检查生日日期是否正确 
            if(!strtotime($dtm_birth)){ 
                return FALSE; 
            }else{ 
              //检验18位身份证的校验码是否正确。 
              //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。 
              $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); 
              $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); 
              $sign = 0; 
              for ( $i = 0; $i < 17; $i++ ){ 
                $b = (int) $id{$i}; 
                $w = $arr_int[$i]; 
                $sign += $b * $w; 
              } 
              $n = $sign % 11; 
              $val_num = $arr_ch[$n]; 
              if ($val_num != substr($id,17, 1)){ 
                return FALSE; 
              }else{ 
                return TRUE; 
              } 
            } 
        } 
    }

    public function is_mobile($mobile)
    {        
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            return TRUE;
        }else{
            return FALSE; 
        }
    }

    public function is_bankno($s) {
        $n = 0;
        for ($i = strlen($s); $i >= 1; $i--) {
            $index=$i-1;
            //偶数位
            if ($i % 2==0) {
                $n += $s{$index};
            } else {//奇数位
                $t = $s{$index} * 2;
                if ($t > 9) {
                    $t = (int)($t/10)+ $t%10;
                }
                $n += $t;
            }
        }
        return ($n % 10) == 0;
    }
}